// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// v [author] rhyme_lph
// V [email]  rhymelph@gmail.com
// i [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/dashboard_reimburse_entity.dart';
import 'package:finance_app/src/entities/payslips_entity.dart';
import 'package:finance_app/src/http_service/http_dashboard_service.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/sales_trend_bottom_sheet.dart';

class DashboardOverviewProvider extends BaseProvider {
  String currentSelectSalesTrend;
  PayslipsEntity profileLoss;
  DashboardReimburseEntity expense;
  PayslipsEntity salesTrend;

  @override
  Future get dataFuture => null;

  @override
  void initState() {
    currentSelectSalesTrend = S.current.monthly;

    super.initState();
    onRefreshDashboardOverview();
  }

  void onRefreshDashboardOverview() {
    profileLoss = null;
    refreshSalesTrend();
    post(HttpDashboardService.dashboardExpenses(),
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      expense = getEntityFromResult<DashboardReimburseEntity>(result);
      update();
    });
    post(HttpDashboardService.dashboardProfits(),
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      profileLoss = getEntityFromResult<PayslipsEntity>(result);
      update();
    });
  }

  void refreshSalesTrend({bool showDialog = false}) {
    salesTrend = null;
    post(
        HttpDashboardService.dashboardSalesOverview(
            currentSelectSalesTrend.toLowerCase()),
        autoHandler: showDialog ? AutoHandler.Toast : null,
        loadingTip: showDialog ? S.current.loading : null, onSuccess: (result) {
      salesTrend = getEntityFromResult<PayslipsEntity>(result);
      update();
    });
  }

  void onNavSalesTrend() {
    Routes.navigateTo(RouterGenProviders.dateReportPage, params: {
      'type': 1,
    });
  }

  void onSelectSaleTrend() {
    obtainContext?.call((context) async {
      final result =
          await showSalesTrendBottomSheet(context, currentSelectSalesTrend);
      if (result != currentSelectSalesTrend) {
        currentSelectSalesTrend = result;
        update();
        refreshSalesTrend(showDialog: true);
      }
    });
  }

  void onNavExpenses() {
    Routes.navigateTo(RouterGenProviders.purchasesPage, params: {
      'index': 3,
    });
  }

  void onNavProfitLoss() {
    Routes.navigateTo(RouterGenProviders.dateReportPage, params: {
      'type': 71,
    });
  }
}
